// 视力数据录入模块前端JS（全局唯一配置驱动版，支持查询、录入、历史、导出、日志恢复）

document.addEventListener("DOMContentLoaded", function () {
  let selectedStudent = null;
  let editingRecordId = null;
  let lastSavedRecordId = null;
  // ✅新增：配置驱动支持
  let visionConfig = null;
  let queryFieldsConfig = null;
  let historyFieldsConfig = null;
  let searchResultConfig = null; // 新增：查询结果表格配置

  // ✅新增：加载视力配置（严格配置驱动，无兜底方案）
  async function loadVisionConfig() {
    console.log("🔧 开始加载视力配置...");
    
    // 1. 获取查询字段配置（严格要求成功）
    try {
      const queryFieldsResp = await fetch("/api/config/query-fields");
      if (!queryFieldsResp.ok) {
        throw new Error(`查询字段配置API失败: ${queryFieldsResp.status}`);
      }
      const queryFieldsData = await queryFieldsResp.json();
      if (!queryFieldsData.success) {
        throw new Error(`查询字段配置返回失败: ${queryFieldsData.message}`);
      }
      queryFieldsConfig = queryFieldsData.fields;
      
      renderQueryArea();
    } catch (error) {
      console.error("❌ 查询字段配置加载失败:", error);
      throw new Error(`配置驱动架构要求查询字段配置必须成功: ${error.message}`);
    }
    
    // 2. 获取历史记录字段配置（严格要求成功）
    try {
      const historyFieldsResp = await fetch("/api/config/history_fields/vision");
      if (!historyFieldsResp.ok) {
        throw new Error(`历史字段配置API失败: ${historyFieldsResp.status}`);
      }
      const historyFieldsData = await historyFieldsResp.json();
      if (!historyFieldsData.success) {
        throw new Error(`历史字段配置返回失败: ${historyFieldsData.message}`);
      }
      historyFieldsConfig = historyFieldsData.fields;
      console.log("✅ 历史记录字段配置加载成功:", historyFieldsConfig);
    } catch (error) {
      console.error("❌ 历史字段配置加载失败:", error);
      throw new Error(`配置驱动架构要求历史字段配置必须成功: ${error.message}`);
    }

    // 3. 获取查询结果表格配置（严格要求成功）
    try {
      const searchResultResp = await fetch("/api/config/search_result_fields/vision");
      if (!searchResultResp.ok) {
        throw new Error(`查询结果配置API失败: ${searchResultResp.status}`);
      }
      const searchResultData = await searchResultResp.json();
      if (!searchResultData.success) {
        throw new Error(`查询结果配置返回失败: ${searchResultData.message}`);
      }
      searchResultConfig = searchResultData;
      
    } catch (error) {
      console.error("❌ 查询结果配置加载失败:", error);
      throw new Error(`配置驱动架构要求查询结果配置必须成功: ${error.message}`);
    }
    
    // 4. 获取完整视力配置（严格要求成功）
    try {
      const response = await fetch("/api/config/vision/records");
      if (!response.ok) {
        throw new Error(`视力配置API失败: ${response.status}`);
      }
      const data = await response.json();
      if (!data.success) {
        throw new Error(`视力配置返回失败: ${data.message}`);
      }
      visionConfig = data.config;
      
      // 严格验证API端点配置
      if (!visionConfig.api_config || !visionConfig.api_config.api_endpoints) {
        throw new Error("配置驱动架构错误：缺少API端点配置");
      }
      
      const requiredEndpoints = ['create', 'update', 'delete', 'list', 'logs', 'logs_all'];
      const missingEndpoints = requiredEndpoints.filter(endpoint => 
        !visionConfig.api_config.api_endpoints[endpoint]
      );
      
      if (missingEndpoints.length > 0) {
        throw new Error(`配置驱动架构错误：缺少必需的API端点配置: ${missingEndpoints.join(', ')}`);
      }
      
      console.log("✅ 视力配置加载成功:", visionConfig);
      console.log("✅ API端点配置验证通过:", visionConfig.api_config.api_endpoints);
      
      // 初始化表单配置
      initializeFormWithConfig();
    } catch (error) {
      console.error("❌ 视力配置加载失败:", error);
      throw new Error(`配置驱动架构要求视力配置必须成功: ${error.message}`);
    }
    
    console.log("✅ 所有配置加载完成，配置驱动架构初始化成功");
  }

  // ✅新增：使用FixedQueryArea渲染查询区
  function renderQueryArea() {
    if (!queryFieldsConfig) {
      console.warn("⚠️ 查询配置未加载，跳过查询区渲染");
      return;
    }
    

    
    if (window.renderFixedQueryArea) {
      window.renderFixedQueryArea(
        queryFieldsConfig,
        "fixedQueryArea",
        onSearch,
        onClear,
        false // 禁用列配置按钮
      );
    } else {
      console.error("❌ FixedQueryArea.js 未正确加载");
    }
  }

  // ✅新增：查询按钮回调（严格配置驱动）
  async function onSearch(params) {
    // 严格检查查询结果配置
    if (!searchResultConfig || !searchResultConfig.columns) {
      console.error("❌ 查询结果配置未加载，无法执行查询");
      if (window.Swal) {
        Swal.fire("配置错误", "查询结果配置未加载，请刷新页面重试", "error");
      }
      return;
    }
    
    // 添加分页参数
    const searchParams = new URLSearchParams(params);
    const page = params.page || '1';
    searchParams.set('page', page);
    searchParams.set('per_page', '10');
    
    // 使用配置API提供的列配置（严格配置驱动）
    searchParams.set('columns', searchResultConfig.columns.join(','));
    
    
    // 调用统一查询接口
    fetch(`/api/students/query?${searchParams.toString()}`)
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
      })
      .then((data) => {
        console.log(`✅ 查询成功，共 ${data.total} 条记录，当前第 ${data.page} 页`);
        if (data.success) {
          // 严格配置驱动：API响应数据完整性验证
          if (data.students === undefined || data.total === undefined || data.page === undefined || data.per_page === undefined) {
            throw new Error("配置驱动架构错误：API响应数据不完整，必须包含 students, total, page, per_page 字段");
          }
          
          const students = data.students;
          const total = data.total;
          const pageNum = data.page;
          const perPage = data.per_page;
          
          renderStudentTableWithComponent(students);
          renderPagination(total, pageNum, perPage);
        } else {
          console.error("❌ 查询失败:", data.message || data.error);
          renderStudentTableWithComponent([]);
          if (window.Swal) {
            Swal.fire("查询失败", data.message || data.error || "未知错误", "error");
          }
        }
      })
      .catch((error) => {
        console.error("❌ 查询异常:", error);
        renderStudentTableWithComponent([]);
        if (window.Swal) {
          Swal.fire("查询失败", `网络或服务器错误: ${error.message}`, "error");
        }
      });
  }

  // ✅新增：清除按钮回调
  function onClear() {
    renderStudentTableWithComponent([]);
    renderPagination(0, 1, 10);
  }

  // ✅新增：获取当前查询参数
  function getCurrentQueryParams() {
    const params = {};
    const queryInputs = document.querySelectorAll('#fixedQueryArea input, #fixedQueryArea select');
    queryInputs.forEach(input => {
      if (input.value && input.name) {
        params[input.name] = input.value;
      }
    });
    return params;
  }

  // ✅增强：使用配置初始化表单（完全配置驱动）
  function initializeFormWithConfig() {
    if (!visionConfig) {
      console.warn("⚠️ 配置未加载，跳过表单初始化");
      return;
    }

    console.log("🔧 开始配置化表单初始化，配置内容:", visionConfig);

    // ✅新增：基于ALL_FIELD_CONFIG_REGISTRY动态生成所有下拉选项
    if (visionConfig.form_fields) {
      visionConfig.form_fields.forEach(fieldConfig => {
        if (fieldConfig.input_type === 'select' && fieldConfig.options) {
          const selectElement = document.querySelector(`[name="${fieldConfig.field}"]`);
          if (selectElement) {
            console.log(`🔧 配置化字段 ${fieldConfig.field}，选项数量:`, fieldConfig.options.length);
            
            // 清空现有选项
            selectElement.innerHTML = "";
            
            // 添加默认选项
            if (fieldConfig.field !== 'measure_type') { // 检查类型不需要默认选项
              const defaultOption = document.createElement("option");
              defaultOption.value = "";
              defaultOption.textContent = `请选择${fieldConfig.display_name}`;
              selectElement.appendChild(defaultOption);
            }
            
            // 动态添加选项
            fieldConfig.options.forEach((option, index) => {
              console.log(`添加选项 ${index}:`, option);
              const optionElement = document.createElement("option");
              optionElement.value = option;
              optionElement.textContent = option;
              selectElement.appendChild(optionElement);
            });
            
            console.log(`✅ 字段 ${fieldConfig.field} 选项生成完成`);
          }
        }
      });
    }

    // ✅修复：使用配置的前端配置更新字段标签
    if (visionConfig.frontend_config && visionConfig.frontend_config.field_labels) {
      console.log("🔧 应用配置化字段标签");
      Object.keys(visionConfig.frontend_config.field_labels).forEach((fieldName) => {
        const field = document.querySelector(`[name="${fieldName}"]`);
        if (field) {
          const label = field
            .closest(".col-md-3, .col-md-4, .col-md-12, .col-md-2")
            ?.querySelector("label");
          if (label) {
            label.textContent = visionConfig.frontend_config.field_labels[fieldName];
          }
        }
      });
    }

    console.log("✅ 表单配置化初始化完成");
  }

  // 初始化隐藏学生信息条
  const studentInfoBar = document.getElementById("student-info-bar");
  if (studentInfoBar) {
    studentInfoBar.classList.remove("show");
  }

  // 统一的URL参数处理函数
  function initializeFromParams() {
    try {
      const urlParams = new URLSearchParams(window.location.search);
      const studentId = urlParams.get("student_id");
      const autoExpand = urlParams.get("auto_expand");
      const fromComplete = urlParams.get("fromComplete") || urlParams.get("from_complete"); // 兼容两种参数名
      const showHistory = urlParams.get("show_history");

      console.log("=== 视力录入页面初始化 ===");
      console.log("URL参数:", Object.fromEntries(urlParams));

      if (studentId && autoExpand === "true") {
        console.log("✅ 开始自动加载学生信息");

        if (fromComplete === "true") {
          // 修复：正确获取学生姓名，使用 'name' 而不是 'student_name'
          const studentFromUrl = {
            id: parseInt(studentId),
            name: urlParams.get("name") || "", // 修复：直接使用 'name' 参数
            education_id: urlParams.get("education_id") || "",
            school: urlParams.get("school") || "",
            class_name: urlParams.get("class_name") || "",
            grade: urlParams.get("grade") || "",
            gender: urlParams.get("gender") || "",
            birthday: urlParams.get("birthday") || "",
            parent_name: urlParams.get("parent_name") || "",
          };

          console.log("✅ 从URL构建的学生信息:", studentFromUrl);
          selectedStudent = studentFromUrl;
          fillStudentInfoBar(selectedStudent);

          if (studentInfoBar) {
            studentInfoBar.classList.add("show");
            studentInfoBar.style.display = "flex";
          }

          // 🔧 修复：从学生档案页面跳转时，优先显示历史记录
          if (fromComplete === "true") {
            console.log("✅ 从学生档案页面跳转，显示学生历史记录");
            showHistoryTable(studentId);
          } else if (showHistory === "true") {
            console.log("✅ 显示历史记录表格");
            showHistoryTable(studentId);
          } else {
            console.log("✅ 显示视力录入表单");
            showVisionForm();
          }

          console.log("✅ 学生信息加载完成");
        } else {
          // 通过API加载学生信息
          loadStudentBaseInfo(studentId, () => {
            if (fromComplete === "true") {
              console.log("✅ 从学生档案页面跳转，显示学生历史记录");
              showHistoryTable(studentId);
            } else if (showHistory === "true") {
              showHistoryTable(studentId);
            } else {
              showVisionForm();
            }
            console.log("✅ API学生信息加载完成");
          });
        }

        // 清除URL参数
        const newUrl = window.location.pathname;
        window.history.replaceState({}, document.title, newUrl);
      }
    } catch (error) {
      console.error("初始化参数处理失败:", error);
      if (window.Swal) {
        Swal.fire("错误", "页面初始化失败，请刷新重试", "error");
      }
    }
  }

  // 填充学生基本信息横条（使用统一组件）
  async function fillStudentInfoBar(student) {
    console.log("📝 fillStudentInfoBar 被调用，学生数据:", student);

    try {
      // 使用统一的学生信息条组件
      await renderStudentInfoBar(student, {
        moduleName: 'vision',
        containerId: 'student-info-bar',
        autoShow: true,
        onError: (error) => {
          console.error("❌ 学生信息条组件渲染失败:", error);
          if (window.Swal) {
            Swal.fire("警告", "学生信息显示异常，请刷新页面重试", "warning");
          }
        }
      });

      console.log("✅ 学生信息栏已显示");

    } catch (error) {
      console.error("填充学生信息时出错:", error);
      if (window.Swal) {
        Swal.fire("警告", "学生信息显示异常，请刷新页面重试", "warning");
      }
    }
  }

  // 显示视力录入表单
  function showVisionForm() {
    // 隐藏查询结果
    const searchResults = document.getElementById("search-results");
    if (searchResults) {
      searchResults.style.display = "none";
    }

    const paginationBar = document.getElementById("pagination-bar");
    if (paginationBar) {
      paginationBar.style.display = "none";
    }

    // 显示视力录入表单
    const visionForm = document.getElementById("vision-form");
    if (visionForm) {
      visionForm.style.display = "block";

      // 重置表单
      visionForm.reset();

      // 设置默认值
      const measureDate = visionForm.querySelector('[name="measure_date"]');
      if (measureDate && !measureDate.value) {
        measureDate.value = new Date().toISOString().split("T")[0];
      }

      const measureTime = visionForm.querySelector('[name="measure_time"]');
      if (measureTime && !measureTime.value) {
        const now = new Date();
        measureTime.value = `${now.getHours().toString().padStart(2, "0")}:${now
          .getMinutes()
          .toString()
          .padStart(2, "0")}`;
      }
    }
  }

  // 移除原有search-form事件绑定（已替换为FixedQueryArea）
  // 原代码已移除，现在使用FixedQueryArea组件处理查询

  // ✅新增：选择学生进行视力录入
  function selectStudent(studentId) {
    console.log("🎯 选择学生进行视力录入，学生ID:", studentId);
    loadStudentBaseInfo(studentId, showVisionForm);
  }

  // ✅新增：显示学生历史记录（配置驱动查询按钮）
  function showStudentHistory(studentId) {
    console.log("📊 显示学生历史记录，学生ID:", studentId);
    loadStudentBaseInfo(studentId, () => showHistoryTable(studentId));
  }

  // ✅新增：显示学生基本信息（视力模块查询按钮）
  function showStudentInfo(studentId) {
    console.log("👤 显示学生基本信息，学生ID:", studentId);
    console.log("🔍 开始调用 loadStudentBaseInfo...");
    loadStudentBaseInfo(studentId, (student) => {
      console.log("📞 loadStudentBaseInfo 回调被执行，学生数据:", student);
      if (student) {
        console.log("✅ 学生数据存在，开始填充信息栏和显示历史记录");
        // 显示学生信息并展示历史记录
        fillStudentInfoBar(student);
        console.log("📊 准备调用 showHistoryTable，学生ID:", student.id);
        showHistoryTable(student.id);  // 使用学生对象的id属性
        console.log("✅ showStudentInfo 函数执行完成");
      } else {
        console.error("❌ 学生数据为空或undefined");
      }
    });
  }

  // ✅新增：新增视力记录（视力模块录入按钮）
  function addVisionRecord(studentId) {
    console.log("👁️ 新增视力记录，学生ID:", studentId);
    loadStudentBaseInfo(studentId, (student) => {
      if (student) {
        // 显示学生信息并打开录入表单
        fillStudentInfoBar(student);
        showVisionForm();
      }
    });
  }

  // ✅新增：全局函数声明（供HTML onclick调用）
  window.selectStudent = selectStudent;
  window.showStudentHistory = showStudentHistory;
  window.showStudentInfo = showStudentInfo;
  window.addVisionRecord = addVisionRecord;
  window.showHistoryTable = showHistoryTable; // 添加showHistoryTable的全局暴露

  // ✅使用配置API的表格渲染（完全配置驱动）
  async function renderStudentTableWithComponent(students) {
    if (!window.renderQueryResultTable) {
      console.error("❌ QueryResultTable组件未加载");
      return;
    }

    // 显示结果表格容器
    document.getElementById("search-results").style.display = "block";

    try {
      // 使用新的自包含QueryResultTable API
      await window.renderQueryResultTable(students, 'vision', 'query', {
        showRowNumber: true,
        onRowClick: (row, index) => {
          console.log('点击学生行:', row, index);
        }
      });
      
      console.log('✅ 视力模块表格渲染完成，数据量:', students?.length || 0);
    } catch (error) {
      console.error('❌ 视力模块表格渲染失败:', error);
      
      // 降级处理：显示错误信息
      const tableBody = document.getElementById('queryTableBody');
      if (tableBody) {
        tableBody.innerHTML = `
          <tr>
            <td colspan="100%" class="text-center text-danger py-4">
              <i class="fas fa-exclamation-triangle fa-2x mb-2 d-block"></i>
              <div>表格渲染失败: ${error.message}</div>
            </td>
          </tr>
        `;
      }
    }
  }

  // ✅新增：从全局配置获取字段显示名称
  function getFieldDisplayName(fieldName) {
    // 尝试从ALL_FIELD_CONFIG_REGISTRY获取字段显示名称
    if (visionConfig?.frontend_config?.field_labels?.[fieldName]) {
      return visionConfig.frontend_config.field_labels[fieldName];
    }
    
    // 标准字段映射
    /*const fieldNameMap = {
      'education_id': '教育ID',
      'school': '学校',
      'name': '姓名',
      'gender': '性别',
      'age': '年龄',
      'id_number': '身份证号码',
      'phone': '电话',
      'parent_name': '家长姓名',
      'parent_phone': '家长电话',
      'class_name': '班级',
      'grade': '年级'
    };*/
    
    return fieldNameMap[fieldName] || fieldName;
  }

  // ✅新增：获取历史记录字段显示名称
  function getHistoryFieldDisplayName(fieldName) {
    // 尝试从配置获取字段显示名称
    if (visionConfig?.frontend_config?.field_labels?.[fieldName]) {
      return visionConfig.frontend_config.field_labels[fieldName];
    }
    
    // 视力历史记录字段映射
    const historyFieldNameMap = {
      'measure_date': '检查日期',
      'measure_time': '检查时间',
      'measure_location': '检查地点',
      'measure_type': '检查类型',
      'measurer': '检查人员',
      'right_eye_naked': '右眼裸眼',
      'left_eye_naked': '左眼裸眼',
      'vision_level': '视力等级'
    };
    
    return historyFieldNameMap[fieldName] || fieldName;
  }

  function renderPagination(total, page, per_page) {
    const pageCount = Math.ceil(total / per_page);
    if (pageCount <= 1) {
      document.getElementById("pagination-bar").innerHTML = "";
      return;
    }
    let html = "";
    html += `<button class="page-btn" ${
      page === 1 ? "disabled" : ""
    } data-page="${page - 1}">上一页</button>`;
    let start = Math.max(1, page - 2);
    let end = Math.min(pageCount, page + 2);
    if (start > 1) html += "<span>...</span>";
    for (let i = start; i <= end; i++) {
      html += `<button class="page-btn${
        i === page ? " active" : ""
      }" data-page="${i}">${i}</button>`;
    }
    if (end < pageCount) html += "<span>...</span>";
    html += `<button class="page-btn" ${
      page === pageCount ? "disabled" : ""
    } data-page="${page + 1}">下一页</button>`;
    document.getElementById("pagination-bar").innerHTML = html;
    document.querySelectorAll(".page-btn").forEach((btn) => {
      btn.addEventListener("click", function () {
        const toPage = parseInt(this.getAttribute("data-page"));
        if (!isNaN(toPage) && toPage !== page) {
          // 重新执行查询，传递当前查询参数和页码
          const currentParams = getCurrentQueryParams();
          currentParams.page = toPage;
          onSearch(currentParams);
        }
      });
    });
  }

  function loadStudentBaseInfo(studentId, callback) {
    console.log(`🔍 查询学生信息: student_id=${studentId}`);
    
    // 统一使用student_id参数进行跨表查询
    fetch(`/api/students/get?student_id=${studentId}`)
      .then((res) => res.json())
      .then((data) => {
        if (data.success && data.student) {
          selectedStudent = data.student;
          callback && callback(selectedStudent);  // 修复：传递学生对象给回调函数
        } else {
          if (window.Swal) {
            Swal.fire(
              "获取学生信息失败",
              data.message || "未找到该学生",
              "error"
            );
          } else {
            alert("获取学生信息失败");
          }
        }
      })
      .catch((error) => {
        console.error("获取学生信息失败:", error);
        if (window.Swal) {
          Swal.fire("错误", `获取学生信息失败: ${error.message}`, "error");
        } else {
          alert("获取学生信息失败");
        }
      });
  }

  // 显示视力录入表单
  function showVisionForm(record = null, readonly = false) {
    document.getElementById("search-results").style.display = "none";
    document.getElementById("pagination-bar").style.display = "none";
    document.getElementById("vision-form").reset();
    document.getElementById("vision-form").style.display = "block";
    document.getElementById("history-table-area").style.display = "none";

    if (record) {
      for (const key in record) {
        let el = document.querySelector(`#vision-form [name="${key}"]`);
        if (el) {
          if (key === "measure_date" && record.measure_date) {
            el.value = record.measure_date.split("T")[0];
          } else if (key === "measure_time" && record.measure_time) {
            el.value =
              record.measure_time.length > 5
                ? record.measure_time.slice(0, 5)
                : record.measure_time;
          } else if (key === "measure_location") {
            // 严格配置驱动：地点字段处理
            if (record.measure_location === undefined) {
              console.warn(`⚠️ 记录字段 ${key} 未定义，但继续处理`);
            }
            el.value = record.measure_location || "";
          } else {
            // 严格配置驱动：字段值验证
            if (record[key] === undefined) {
              console.warn(`⚠️ 记录字段 ${key} 未定义，但继续处理`);
            }
            el.value = record[key] || "";
          }
        }
      }
    }

    if (!record) {
      const today = new Date().toISOString().split("T")[0];
      document.querySelector('[name="measure_date"]').value = today;
    }
    Array.from(
      document.querySelectorAll(
        "#vision-form input, #vision-form select, #vision-form textarea"
      )
    ).forEach((el) => {
      el.disabled = !!readonly;
    });

    if (record && record.id) {
      editingRecordId = record.id;
    } else {
      editingRecordId = null;
    }

    // 编辑和PDF导出按钮处理
    let editBtn = document.getElementById("btn-edit-record");
    let pdfBtn = document.getElementById("btn-export-pdf");

    if (readonly && !editBtn) {
      // 添加编辑按钮
      editBtn = document.createElement("button");
      editBtn.id = "btn-edit-record";
      editBtn.type = "button";
      editBtn.className = "btn btn-warning ms-2";
      editBtn.textContent = "编辑";
      editBtn.onclick = () => showVisionForm(record, false);
      document
        .querySelector("#vision-form .mb-3.text-end")
        .appendChild(editBtn);

      // 添加PDF导出按钮
      pdfBtn = document.createElement("button");
      pdfBtn.id = "btn-export-pdf";
      pdfBtn.type = "button";
      pdfBtn.className = "btn btn-danger ms-2";
      pdfBtn.textContent = "导出PDF";
      pdfBtn.onclick = () => exportToPDF(record);
      document.querySelector("#vision-form .mb-3.text-end").appendChild(pdfBtn);
    } else if (!readonly) {
      // 编辑模式下移除这些按钮
      if (editBtn) editBtn.remove();
      if (pdfBtn) pdfBtn.remove();
    }
  }

  // PDF导出功能
  function exportToPDF(record) {
    if (!selectedStudent || !record) {
      alert("缺少必要数据");
      return;
    }

    // 打开新窗口显示PDF预览页面
    const pdfUrl = `/api/vision_records/${record.id}/export_pdf`;
    window.open(pdfUrl, "_blank");
  }

  // 优化的表单提交处理
  const visionForm = document.getElementById("vision-form");
  if (visionForm) {
    visionForm.addEventListener("submit", function (e) {
      e.preventDefault();

      if (!selectedStudent) {
        if (window.Swal) {
          Swal.fire("提示", "请先选择学生", "info");
        } else {
          alert("请先选择学生");
        }
        return;
      }

      // 显示保存中状态
      const submitButton = visionForm.querySelector('button[type="submit"]');
      const originalText = submitButton ? submitButton.textContent : "";
      if (submitButton) {
        submitButton.disabled = true;
        submitButton.textContent = "保存中...";
      }

      try {
        const formData = new FormData(this);
        const payload = {
          // 基础信息
          student_id: selectedStudent.id,
          measure_date: formData.get("measure_date"),
          measure_time: formData.get("measure_time"),
          measure_location: formData.get("measure_location"),
          measure_type: formData.get("measure_type"),
          measurer: formData.get("measurer"),
          is_baseline: formData.get("is_baseline") === "on",
          // 视力数据
          right_eye_naked: parseFloat(formData.get("right_eye_naked")) || null,
          left_eye_naked: parseFloat(formData.get("left_eye_naked")) || null,
          right_eye_corrected:
            parseFloat(formData.get("right_eye_corrected")) || null,
          left_eye_corrected:
            parseFloat(formData.get("left_eye_corrected")) || null,
          // 屈光数据
          right_sphere: parseFloat(formData.get("right_sphere")) || null,
          left_sphere: parseFloat(formData.get("left_sphere")) || null,
          right_cylinder: parseFloat(formData.get("right_cylinder")) || null,
          left_cylinder: parseFloat(formData.get("left_cylinder")) || null,
          right_axis: parseFloat(formData.get("right_axis")) || null,
          left_axis: parseFloat(formData.get("left_axis")) || null,

          // 散瞳数据
          right_dilated_sphere:
            parseFloat(formData.get("right_dilated_sphere")) || null,
          left_dilated_sphere:
            parseFloat(formData.get("left_dilated_sphere")) || null,
          right_dilated_cylinder:
            parseFloat(formData.get("right_dilated_cylinder")) || null,
          left_dilated_cylinder:
            parseFloat(formData.get("left_dilated_cylinder")) || null,
          right_dilated_axis:
            parseFloat(formData.get("right_dilated_axis")) || null,
          left_dilated_axis:
            parseFloat(formData.get("left_dilated_axis")) || null,
          // ✅修复：添加缺失的散瞳视力字段
          right_dilated_vision:
            parseFloat(formData.get("right_dilated_vision")) || null,
          left_dilated_vision:
            parseFloat(formData.get("left_dilated_vision")) || null,
          // 角膜曲率
          right_keratometry_K1:
            parseFloat(formData.get("right_keratometry_K1")) || null,
          left_keratometry_K1:
            parseFloat(formData.get("left_keratometry_K1")) || null,
          right_keratometry_K2:
            parseFloat(formData.get("right_keratometry_K2")) || null,
          left_keratometry_K2:
            parseFloat(formData.get("left_keratometry_K2")) || null,
          // 眼轴和前房深度
          right_axial_length:
            parseFloat(formData.get("right_axial_length")) || null,
          left_axial_length:
            parseFloat(formData.get("left_axial_length")) || null,
          right_anterior_depth:
            parseFloat(formData.get("right_anterior_depth")) || null,
          left_anterior_depth:
            parseFloat(formData.get("left_anterior_depth")) || null,
          // 其他信息
          eye_fatigue: formData.get("eye_fatigue"),
          other_info: formData.get("other_info"),
          // ✅新增：处理新增字段
          equipment_model: formData.get("equipment_model"),
          remarks: formData.get("remarks"),
        };

        // 严格配置驱动：API端点必须从配置获取
        if (!visionConfig?.api_config?.api_endpoints) {
          throw new Error("配置驱动架构错误：API端点配置未加载，无法提交表单");
        }

        let url, method;
        if (editingRecordId) {
          if (!visionConfig.api_config.api_endpoints.update) {
            throw new Error("配置驱动架构错误：更新API端点未配置");
          }
          url = `${visionConfig.api_config.api_endpoints.update}/${editingRecordId}`;
          method = "PUT";
        } else {
          if (!visionConfig.api_config.api_endpoints.create) {
            throw new Error("配置驱动架构错误：创建API端点未配置");
          }
          url = visionConfig.api_config.api_endpoints.create;
          method = "POST";
        }

        fetch(url, {
          method: method,
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        })
          .then((res) => res.json())
          .then((data) => {
            // ✅修复：添加箭头函数语法
            if (data.success) {
              lastSavedRecordId = data.data.id;
              editingRecordId = null;

              if (window.Swal) {
                Swal.fire({
                  icon: "success",
                  title: "保存成功",
                  text: "视力记录已保存！",
                  timer: 1500,
                  showConfirmButton: false,
                }).then(() => {
                  this.reset();
                  this.style.display = "none";
                  showHistoryTable(selectedStudent.id);
                });
              } else {
                alert("保存成功！");
                this.reset();
                this.style.display = "none";
                showHistoryTable(selectedStudent.id);
              }
            } else {
              throw new Error(data.error || "保存失败");
            }
          })
          .catch((err) => {
            console.error("保存失败:", err);
            if (window.Swal) {
              Swal.fire("保存失败", err.message, "error");
            } else {
              alert("保存失败：" + err.message);
            }
          })
          .finally(() => {
            // 恢复按钮状态
            if (submitButton) {
              submitButton.disabled = false;
              submitButton.textContent = originalText;
            }
          });
      } catch (error) {
        // ✅修复：正确的catch语法
        console.error("表单处理失败:", error);
        if (window.Swal) {
          Swal.fire("错误", "表单数据处理失败", "error");
        } else {
          alert("表单数据处理失败");
        }

        // 恢复按钮状态
        if (submitButton) {
          submitButton.disabled = false;
          submitButton.textContent = originalText;
        }
      }
    });
  }

  function showHistoryTable(studentId) {
    console.log("🔍 showHistoryTable 被调用，学生ID:", studentId);
    console.log("📋 当前 historyFieldsConfig 状态:", historyFieldsConfig);
    
    // 检查配置是否已加载
    if (!historyFieldsConfig) {
      console.error("❌ 历史字段配置未加载，等待配置加载完成...");
      
      // 等待配置加载完成后重试
      setTimeout(() => {
        console.log("⏰ 配置重试检查，historyFieldsConfig:", historyFieldsConfig);
        if (historyFieldsConfig) {
          console.log("✅ 配置已加载，重新调用 showHistoryTable");
          showHistoryTable(studentId);
        } else {
          console.error("❌ 配置加载超时，无法显示历史记录");
          alert("配置加载失败，请刷新页面重试");
        }
      }, 1000);
      return;
    }
    
    document.getElementById("search-results").style.display = "none";
    document.getElementById("pagination-bar").style.display = "none";
    document.getElementById("vision-form").style.display = "none";
    
    const area = document.getElementById("history-table-area");
    console.log("📍 历史记录区域元素:", area);
    
    if (area) {
      area.classList.add("show");
      area.style.display = "block";
      console.log("✅ 历史记录区域已显示");
    } else {
      console.error("❌ 找不到历史记录区域元素 #history-table-area");
      return;
    }
    
    console.log("📡 开始调用API:", visionConfig?.api_endpoints?.list || `/api/vision_records/list?student_id=${studentId}`);
    
    // 严格配置驱动：使用配置的API端点
    const apiUrl = visionConfig?.api_config?.api_endpoints?.list 
      ? `${visionConfig.api_config.api_endpoints.list}?student_id=${studentId}`
      : `/api/vision_records/list?student_id=${studentId}`;
    
    fetch(apiUrl)
      .then((res) => res.json())
      .then((data) => {
        console.log("📊 API响应数据:", data);
        if (data.success) {
          console.log("✅ API成功，记录数:", data.data ? data.data.length : 0);
          renderHistoryTable(data.data || []);
        } else {
          console.error("❌ API返回失败:", data.message);
        }
      })
      .catch((error) => {
        console.error("❌ API调用异常:", error);
      });
  }

  // ✅重构：配置驱动的历史记录表格渲染（与随访模块架构一致）
  function renderHistoryTable(records) {
    console.log("🎨 renderHistoryTable 被调用，记录数:", records.length);
    console.log("📋 记录数据:", records);
    
    // 修正选择器：使用正确的HTML结构选择器
    const tableHeader = document.querySelector("#history-table thead tr");
    const tbody = document.querySelector("#history-table tbody");
    
    console.log("📍 表格元素检查:");
    console.log("  - tableHeader:", tableHeader);
    console.log("  - tbody:", tbody);
    
    if (!tableHeader || !tbody) {
      console.error("❌ 历史记录表格元素不存在，HTML结构可能有问题");
      return;
    }
    
    // 清空表格
    tableHeader.innerHTML = "";
    tbody.innerHTML = "";
    console.log("🧹 表格已清空");
    
    if (!records.length) {
      tbody.innerHTML = `<tr><td colspan="100%" class="text-center text-muted">暂无历史记录</td></tr>`;
      console.log("📝 显示无记录提示");
      return;
    }

    // 使用配置驱动的历史表格字段
    console.log("⚙️ 历史字段配置检查:", historyFieldsConfig);
    
    if (!historyFieldsConfig || !Array.isArray(historyFieldsConfig) || historyFieldsConfig.length === 0) {
      console.error("❌ 历史字段配置未加载或格式错误，无法渲染表格");
      tbody.innerHTML = `<tr><td colspan="100%" class="text-center text-danger">配置加载失败，请刷新页面重试</td></tr>`;
      return;
    }
    
    console.log("✅ 使用API配置的历史字段:", historyFieldsConfig);

    // 动态生成表头 - 直接使用后端配置的display_name
    console.log("🏗️ 开始生成表头...");
    
    historyFieldsConfig.forEach((fieldConfig) => {
      if (!fieldConfig || !fieldConfig.field || !fieldConfig.display_name) {
        console.warn("⚠️ 无效的字段配置:", fieldConfig);
        return;
      }
      
      const th = document.createElement("th");
      th.textContent = fieldConfig.display_name;  // 直接使用后端配置的表头名称
      console.log(`  添加表头: ${fieldConfig.field} -> ${fieldConfig.display_name}`);
      
      tableHeader.appendChild(th);
    });
    
    console.log("✅ 表头生成完成，列数:", tableHeader.children.length);

    // 渲染历史记录数据行 - 使用正确的配置驱动逻辑
    console.log("🏗️ 开始渲染数据行...");
    records.forEach((record, recordIndex) => {
      const row = document.createElement("tr");
      console.log(`  渲染第${recordIndex + 1}条记录:`, record.id);
      
      historyFieldsConfig.forEach((fieldConfig, fieldIndex) => {
        const td = document.createElement("td");
        
        if (fieldConfig && fieldConfig.field) {
          if (fieldConfig.field === 'actions') {
            // 操作按钮 - 配置驱动渲染
            let buttons = '';
            if (fieldConfig.buttons && Array.isArray(fieldConfig.buttons)) {
              buttons = fieldConfig.buttons.map(btn => {
                if (btn === "详情") {
                  return `<button class="btn btn-outline-primary btn-sm me-1 btn-show-detail" data-id="${record.id}" title="查看详细信息">
                    <i class="bi bi-eye"></i> 详情
                  </button>`;
                } else if (btn === "删除") {
                  return `<button class="btn btn-outline-danger btn-sm me-1 btn-delete-record" data-id="${record.id}" title="删除该记录">
                    <i class="bi bi-trash"></i> 删除
                  </button>`;
                } else if (btn === "日志") {
                  return `<button class="btn btn-outline-info btn-sm me-1 btn-log-record" data-id="${record.id}" title="查看修改日志">
                    <i class="bi bi-clock-history"></i> 日志
                  </button>`;
                } else {
                  return `<button class="btn btn-secondary btn-sm me-1" disabled>${btn}</button>`;
                }
              }).join('');
            }
            td.innerHTML = buttons;
            console.log(`    操作列: ${buttons ? '已添加按钮' : '无按钮'}`);
          } else {
            // 常规字段 - 严格配置驱动处理
            let value = record[fieldConfig.field];
            
            // 对未定义字段进行警告但继续处理
            if (value === undefined) {
              console.warn(`⚠️ 历史记录字段 ${fieldConfig.field} 未定义，记录ID: ${record.id}`);
              value = '';
            }
            
            // 特殊字段格式化
            if (fieldConfig.field === 'measure_date' && value) {
              value = value.split("T")[0];
            } else if (fieldConfig.field === 'measure_time' && value) {
              value = value.slice(0, 5);
            }
            
            td.textContent = value;
            console.log(`    字段${fieldIndex}: ${fieldConfig.field} = ${value}`);
          }
        } else {
          console.warn("⚠️ 无效的字段配置:", fieldConfig);
          td.textContent = "";
        }
        
        row.appendChild(td);
      });
      
      tbody.appendChild(row);
    });

    console.log(`✅ 配置驱动历史记录表格渲染完成，共 ${records.length} 条记录`);

    // 修复：重新绑定详情按钮事件监听器，严格配置驱动（无兜底方案）
    document.querySelectorAll(".btn-show-detail").forEach((btn) => {
      btn.addEventListener("click", function () {
        const recordId = btn.dataset.id;
        console.log("点击详情按钮，记录ID:", recordId);

        // 严格配置驱动：要求本地数据必须可用，不可用时抛出配置错误
        const recordData = records.find((r) => r.id == recordId);
        if (recordData) {
          console.log("✅ 使用配置驱动本地数据显示详情:", recordData);
          showVisionForm(recordData, true);
          return;
        }

        // 严格配置驱动架构：本地数据不可用时，暴露问题并中断操作
        const errorMessage = `配置驱动架构错误：记录ID ${recordId} 在本地数据中不存在。这违反了配置驱动原则，必须修复数据加载逻辑。`;
        console.error("❌ 配置驱动架构错误:", errorMessage);
        if (window.Swal) {
          Swal.fire("配置驱动架构错误", errorMessage, "error");
        } else {
          alert(`配置驱动架构错误: ${errorMessage}`);
        }
        throw new Error(errorMessage);
      });
    });

    // 删除功能实现
    document.querySelectorAll(".btn-delete-record").forEach((btn) => {
      btn.addEventListener("click", function () {
        const recordId = btn.dataset.id;
        if (window.Swal) {
          Swal.fire({
            title: "确定要删除该视力记录吗？",
            text: "删除后将无法恢复，但可通过日志查看历史记录",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "确定删除",
            cancelButtonText: "取消",
            confirmButtonColor: "#d33",
          }).then((result) => {
            if (result.isConfirmed) {
              // 严格配置驱动：使用配置的删除API端点
              const deleteUrl = visionConfig?.api_config?.api_endpoints?.delete 
                ? `${visionConfig.api_config.api_endpoints.delete}/${recordId}`
                : `/api/vision_records/${recordId}`;
                
              fetch(deleteUrl, {
                method: "DELETE",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ operator: "用户" }),
              })
                .then((res) => res.json())
                .then((data) => {
                  if (data.success) {
                    Swal.fire({
                      title: "删除成功",
                      text: "视力记录已删除",
                      icon: "success",
                      timer: 1500,
                    });
                    showHistoryTable(selectedStudent.id);
                  } else {
                    Swal.fire("删除失败", data.error || "未知错误", "error");
                  }
                })
                .catch((err) => {
                  Swal.fire("删除失败", "网络错误：" + err.message, "error");
                });
            }
          });
        } else {
          if (!confirm("确定要删除该视力记录吗？删除后将无法恢复！")) return;
          // 严格配置驱动：使用配置的删除API端点
          const deleteUrl = visionConfig?.api_config?.api_endpoints?.delete 
            ? `${visionConfig.api_config.api_endpoints.delete}/${recordId}`
            : `/api/vision_records/${recordId}`;
            
          fetch(deleteUrl, {
            method: "DELETE",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ operator: "用户" }),
          })
            .then((res) => res.json())
            .then((data) => {
              if (data.success) {
                alert("删除成功");
                showHistoryTable(selectedStudent.id);
              } else {
                alert("删除失败：" + (data.error || "未知错误"));
              }
            });
        }
      });
    });

    // 日志功能实现
    document.querySelectorAll(".btn-log-record").forEach((btn) => {
      btn.addEventListener("click", function () {
        const recordId = btn.dataset.id;
        // 严格配置驱动：使用配置的日志API端点
        const logsUrl = visionConfig?.api_config?.api_endpoints?.logs 
          ? `${visionConfig.api_config.api_endpoints.logs}?record_id=${recordId}`
          : `/api/vision_records/logs?record_id=${recordId}`;
          
        fetch(logsUrl)
          .then((res) => res.json())
          .then((data) => {
            if (data.success && data.data.length > 0) {
              let html = data.data
                .map((log) => {
                  let localTime = log.created_at
                    ? new Date(log.created_at).toLocaleString()
                    : "";
                  let restoreButton = "";

                  // 根据日志类型显示不同的恢复按钮
                  const actionLower = log.action.toLowerCase();
                  if (actionLower === "delete") {
                    restoreButton = `<button class="btn btn-sm btn-outline-success mt-2" onclick="restoreDeletedRecord(${log.id})">恢复已删除记录</button>`;
                  } else if (actionLower === "restore") {
                    restoreButton = `<span class="badge bg-info mt-2">恢复操作记录</span>`;
                  } else if (
                    log.old_content &&
                    (actionLower === "create" || actionLower === "update")
                  ) {
                    restoreButton = `<button class="btn btn-sm btn-outline-primary mt-2" onclick="restoreVisionLog(${log.id})">恢复此版本</button>`;
                  }

                  return `<div style="border-bottom:1px solid #eee;margin-bottom:12px;padding-bottom:8px;">
                <div><strong>记录ID：</strong>${
                  log.record_id
                } | <strong>操作类型：</strong>${
                    log.action
                  } | <strong>操作人：</strong>${
                    log.operator || ""
                  } | <strong>时间：</strong>${localTime}</div>
                ${
                  log.new_content
                    ? `<div><strong>当前内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#e8f5e8;padding:8px;border-radius:4px;border-left:4px solid #28a745;">${log.new_content}</pre></div>`
                    : ""
                }
                ${
                  log.old_content
                    ? `<div><strong>历史内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#fff3cd;padding:8px;border-radius:4px;border-left:4px solid #ffc107;">${
                        log.old_content
                      }</pre>${
                        restoreButton
                          ? `<div style="margin-top:8px;">${restoreButton}</div>`
                          : ""
                      }</div>`
                    : ""
                }
                </div>`;
                })
                .join("");

              if (window.Swal) {
                Swal.fire({
                  title: `${
                    selectedStudent.name || "该学生"
                  }的全部视力记录日志`,
                  html: `<div style="max-height:600px;overflow-y:auto;text-align:left;">${html}</div>`,
                  width: 1000,
                  showConfirmButton: false,
                  showCloseButton: true,
                });
              } else {
                alert("日志功能需要引入 SweetAlert2 支持美观弹窗。");
              }
            } else {
              if (window.Swal) {
                Swal.fire("无日志", "该学生暂无视力记录历史日志", "info");
              } else {
                alert("该学生暂无视力记录历史日志");
              }
            }
          })
          .catch((err) => {
            if (window.Swal) {
              Swal.fire("获取日志失败", "网络错误：" + err.message, "error");
            } else {
              alert("获取日志失败：" + err.message);
            }
          });
      });
    });

    // 渲染完表格后重新绑定按钮
    if (typeof bindStudentRecordBtn === "function") {
      bindStudentRecordBtn();
    }
  }

  document.getElementById("btn-back")?.addEventListener("click", function () {
    document.getElementById("vision-form").style.display = "none";
    document.getElementById("student-info-bar").classList.remove("show");
    document.getElementById("search-results").style.display = "block";
    document.getElementById("pagination-bar").style.display = "block";
    const area = document.getElementById("history-table-area");
    area.classList.remove("show");
    area.style.display = "none";
  });

  document
    .getElementById("btn-show-all")
    ?.addEventListener("click", function () {
      if (!selectedStudent || !selectedStudent.id) {
        alert("请先选择学生！");
        return;
      }
      showHistoryTable(selectedStudent.id);
    });

  document
    .getElementById("btn-export-xlsx-history")
    ?.addEventListener("click", function () {
      if (!selectedStudent) {
        if (window.Swal) {
          Swal.fire("提示", "请先选择学生", "info");
        } else {
          alert("请先选择学生");
        }
        return;
      }

      // 添加调试信息，便于排查问题
      console.log("📊 导出Excel - 学生信息:", selectedStudent);
      console.log(
        "📊 导出URL:",
        `/api/vision_records/export?student_id=${selectedStudent.id}&type=xlsx`
      );

      // 导出Excel文件
      window.open(
        `/api/vision_records/export?student_id=${selectedStudent.id}&type=xlsx`
      );
    });

  // 删除CSV导出按钮事件监听器 - 根据你的要求只保留Excel
  document
    .getElementById("btn-export-csv-history")
    ?.addEventListener("click", function () {
      if (window.Swal) {
        Swal.fire("提示", "已取消CSV导出功能，请使用Excel导出", "info");
      } else {
        alert("已取消CSV导出功能，请使用Excel导出");
      }
    });

  document
    .getElementById("btn-export-xlsx")
    ?.addEventListener("click", function () {
      // 检查是否在查看具体记录详情
      if (editingRecordId || lastSavedRecordId) {
        const recordId = editingRecordId || lastSavedRecordId;
        console.log("📊 导出Excel（详情页面）- 记录ID:", recordId);
        window.open(`/api/vision_records/${recordId}/export_excel`);
      } else if (selectedStudent) {
        // 如果没有具体记录，导出该学生的所有记录
        console.log("📊 导出Excel（表单区域）- 学生信息:", selectedStudent);
        window.open(
          `/api/vision_records/export?student_id=${selectedStudent.id}&type=xlsx`
        );
      } else {
        if (window.Swal) {
          Swal.fire("提示", "请先选择学生或查看具体记录", "info");
        } else {
          alert("请先选择学生或查看具体记录");
        }
        return;
      }
    });

  // 删除CSV导出按钮事件监听器
  document
    .getElementById("btn-export-csv")
    ?.addEventListener("click", function () {
      if (window.Swal) {
        Swal.fire("提示", "已取消CSV导出功能，请使用Excel导出", "info");
      } else {
        alert("已取消CSV导出功能，请使用Excel导出");
      }
    });

  // 查看全部日志功能实现
  document
    .getElementById("btn-view-all-logs")
    ?.addEventListener("click", function () {
      if (!selectedStudent || !selectedStudent.id) {
        if (window.Swal) {
          Swal.fire("提示", "请先选择学生！", "info");
        } else {
          alert("请先选择学生！");
        }
        return;
      }

      // 严格配置驱动：使用配置的日志API端点
      const allLogsUrl = visionConfig?.api_config?.api_endpoints?.logs_all 
        ? `${visionConfig.api_config.api_endpoints.logs_all}?student_id=${selectedStudent.id}`
        : `/api/vision_records/logs_all?student_id=${selectedStudent.id}`;
        
      fetch(allLogsUrl)
        .then((res) => res.json())
        .then((data) => {
          if (data.success && data.data.length > 0) {
            let html = data.data
              .map((log) => {
                let localTime = log.created_at
                  ? new Date(log.created_at).toLocaleString()
                  : "";
                let restoreButton = "";

                // 根据日志类型显示不同的恢复按钮
                const actionLower = log.action.toLowerCase();
                if (actionLower === "delete") {
                  restoreButton = `<button class="btn btn-sm btn-outline-success mt-2" onclick="restoreDeletedRecord(${log.id})">恢复已删除记录</button>`;
                } else if (actionLower === "restore") {
                  restoreButton = `<span class="badge bg-info mt-2">恢复操作记录</span>`;
                } else if (
                  log.old_content &&
                  (actionLower === "create" || actionLower === "update")
                ) {
                  restoreButton = `<button class="btn btn-sm btn-outline-primary mt-2" onclick="restoreVisionLog(${log.id})">恢复此版本</button>`;
                }

                return `<div style="border-bottom:1px solid #eee;margin-bottom:12px;padding-bottom:8px;">
              <div><strong>记录ID：</strong>${
                log.record_id
              } | <strong>操作类型：</strong>${
                  log.action
                } | <strong>操作人：</strong>${
                  log.operator || ""
                } | <strong>时间：</strong>${localTime}</div>
              ${
                log.new_content
                  ? `<div><strong>当前内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#e8f5e8;padding:8px;border-radius:4px;border-left:4px solid #28a745;">${log.new_content}</pre></div>`
                  : ""
              }
              ${
                log.old_content
                  ? `<div><strong>历史内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#fff3cd;padding:8px;border-radius:4px;border-left:4px solid #ffc107;">${
                      log.old_content
                    }</pre>${
                      restoreButton
                        ? `<div style="margin-top:8px;">${restoreButton}</div>`
                        : ""
                    }</div>`
                  : ""
              }
            </div>`;
              })
              .join("");

            if (window.Swal) {
              Swal.fire({
                title: `${selectedStudent.name || "该学生"}的全部视力记录日志`,
                html: `<div style="max-height:600px;overflow-y:auto;text-align:left;">${html}</div>`,
                width: 1000,
                showConfirmButton: false,
                showCloseButton: true,
              });
            } else {
              alert("日志功能需要引入 SweetAlert2 支持美观弹窗。");
            }
          } else {
            if (window.Swal) {
              Swal.fire("无日志", "该学生暂无视力记录历史日志", "info");
            } else {
              alert("该学生暂无视力记录历史日志");
            }
          }
        })
        .catch((err) => {
          if (window.Swal) {
            Swal.fire("获取日志失败", "网络错误：" + err.message, "error");
          } else {
            alert("获取日志失败：" + err.message);
          }
        });
    });

  // --- 学生档案按钮事件绑定（仅在历史表格底部按钮区出现，避免冗余）---
  function bindStudentRecordBtn() {
    const btnStudentRecord = document.getElementById("btn-student-record");
    if (btnStudentRecord) {
      // 先移除所有旧事件，防止重复绑定
      btnStudentRecord.replaceWith(btnStudentRecord.cloneNode(true));
      const newBtn = document.getElementById("btn-student-record");
      newBtn.addEventListener("click", function () {
        let studentId = null;
        if (
          window.selectedStudent &&
          (window.selectedStudent.student_id || window.selectedStudent.id)
        ) {
          studentId =
            window.selectedStudent.student_id || window.selectedStudent.id;
        } else if (
          selectedStudent &&
          (selectedStudent.student_id || selectedStudent.id)
        ) {
          studentId = selectedStudent.student_id || selectedStudent.id;
        }
        if (!studentId) {
          if (window.Swal) {
            Swal.fire("无法跳转", "请先选择一名学生后再查看档案。", "warning");
          } else {
            alert("请先选择一名学生后再查看档案。");
          }
          return;
        }
        window.open(
          `/student-complete-record?student_id=${encodeURIComponent(
            studentId
          )}`,
          "_blank"
        );
      });
    }
  }

  // 页面加载完成后先加载配置再初始化（严格配置驱动）
  async function initializeApp() {
    try {
      await loadVisionConfig();
      initializeFromParams();
      // 初始化时也绑定一次，防止首次渲染无效
      if (typeof bindStudentRecordBtn === "function") {
        bindStudentRecordBtn();
      }
      console.log("✅ 应用初始化完成，配置驱动架构正常运行");
    } catch (error) {
      console.error("❌ 应用初始化失败，配置驱动架构无法启动:", error);
      // 向用户暴露问题，而不是掩盖
      if (window.Swal) {
        Swal.fire({
          icon: "error",
          title: "配置加载失败",
          html: `<div style="text-align:left;">
            <p><strong>错误原因：</strong>${error.message}</p>
            <p><strong>解决方案：</strong></p>
            <ul>
              <li>检查后端配置API是否正常运行</li>
              <li>确认配置数据是否完整</li>
              <li>联系系统管理员</li>
            </ul>
          </div>`,
          showConfirmButton: true,
          confirmButtonText: "刷新页面重试",
          allowOutsideClick: false
        }).then(() => {
          window.location.reload();
        });
      } else {
        alert(`配置加载失败：${error.message}\n请刷新页面重试或联系系统管理员`);
        throw error; // 抛出错误，确保问题得到暴露
      }
    }
  }

  // 页面加载完成后初始化
  initializeApp();
});

// 处理点击学生行的事件
document.addEventListener("click", function (event) {
  if (event.target.classList.contains("student-row")) {
    const studentId = event.target.dataset.studentId;
    const studentInfoBar = document.getElementById("student-info-bar");
    if (studentInfoBar) {
      studentInfoBar.classList.remove("show");
    }
    
    // 延迟处理点击事件，避免与其他事件冲突
    setTimeout(() => {
      // 移除所有学生行的选中状态
      document.querySelectorAll(".student-row").forEach(row => {
        row.classList.remove("selected");
      });
      
      // 添加当前行的选中状态
      event.target.classList.add("selected");
      
      // 异步显示学生信息条
      fillStudentInfoBar(selectedStudent);
      
      if (studentInfoBar) {
        studentInfoBar.classList.add("show");
        studentInfoBar.style.display = "flex";
      }
    }, 100);
  }
});

// 处理表格操作按钮
document.getElementById("queryTableBody").addEventListener("click", function (event) {
  const clickedElement = event.target;
  if (clickedElement.tagName === "BUTTON") {
    const studentId = clickedElement.dataset.studentId;
    const action = clickedElement.dataset.action;
    
    if (action === "query") {
      // 查询按钮 - 显示学生信息条
      loadStudentBaseInfo(studentId, (student) => {
        fillStudentInfoBar(student);
      });
    } else if (action === "record") {
      // 录入按钮 - 加载学生信息并显示表单
      loadStudentBaseInfo(studentId, showVisionForm);
    }
  }
});

// 恢复视力记录日志的全局函数
window.restoreVisionLog = function (logId) {
  if (window.Swal) {
    Swal.fire({
      title: "确认恢复？",
      text: "恢复后将以该历史内容覆盖当前记录，是否继续？",
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "确定恢复",
      cancelButtonText: "取消",
      confirmButtonColor: "#28a745",
    }).then((result) => {
      if (result.isConfirmed) {
        fetch("/api/vision_records/restore", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ log_id: logId, operator: "用户" }),
        })
          .then((res) => res.json())
          .then((data) => {
            if (data.success) {
              let successMessage = "历史记录已成功恢复";
              let detailsHtml = "";

              // 如果后端返回了变更信息，显示详细信息
              if (data.changes && data.changes.length > 0) {
                successMessage =
                  data.message ||
                  `恢复成功，共变更${data.changes.length}个字段`;
                detailsHtml = `<div style="text-align:left;margin-top:10px;">
                  <strong>变更详情：</strong><br/>
                  ${data.changes.map((change) => `• ${change}`).join("<br/>")}
                </div>`;
              }

              Swal.fire({
                title: "恢复成功",
                html: successMessage + detailsHtml,
                icon: "success",
                timer: detailsHtml ? 3000 : 1500,
                showConfirmButton: detailsHtml ? true : false,
              });
              // 刷新历史表
              if (window.selectedStudent) {
                showHistoryTable(window.selectedStudent.id);
              }
            } else {
              Swal.fire(
                "恢复失败",
                data.message || data.error || "未知错误",
                "error"
              );
            }
          })
          .catch((err) => {
            Swal.fire("恢复失败", "网络错误：" + err.message, "error");
          });
      }
    });
  } else {
    if (confirm("确认恢复该历史记录吗？")) {
      fetch("/api/vision_records/restore", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ log_id: logId, operator: "用户" }),
      })
        .then((res) => res.json())
        .then((data) => {
          if (data.success) {
            alert("恢复成功");
            if (window.selectedStudent) {
              showHistoryTable(window.selectedStudent.id);
            }
          } else {
            alert("恢复失败：" + (data.message || data.error || "未知错误"));
          }
        });
    }
  }
};

// 恢复已删除记录的全局函数
window.restoreDeletedRecord = function (logId) {
  if (window.Swal) {
    Swal.fire({
      title: "确认恢复已删除的记录？",
      text: "将重新创建该记录，是否继续？",
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "确定恢复",
      cancelButtonText: "取消",
      confirmButtonColor: "#28a745",
    }).then((result) => {
      if (result.isConfirmed) {
        fetch("/api/vision_records/restore_deleted", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ log_id: logId, operator: "用户" }),
        })
          .then((res) => res.json())
          .then((data) => {
            if (data.success) {
              Swal.fire({
                title: "恢复成功",
                text: "已删除的记录已成功恢复",
                icon: "success",
                timer: 1500,
              });
              // 刷新历史表
              if (window.selectedStudent) {
                showHistoryTable(window.selectedStudent.id);
              }
            } else {
              Swal.fire(
                "恢复失败",
                data.message || data.error || "未知错误",
                "error"
              );
            }
          })
          .catch((err) => {
            Swal.fire("恢复失败", "网络错误：" + err.message, "error");
          });
      }
    });
  } else {
    if (confirm("确认恢复该已删除记录吗？")) {
      fetch("/api/vision_records/restore_deleted", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ log_id: logId, operator: "用户" }),
      })
        .then((res) => res.json())
        .then((data) => {
          if (data.success) {
            alert("恢复成功");
            if (window.selectedStudent) {
              showHistoryTable(window.selectedStudent.id);
            }
          } else {
            alert("恢复失败：" + (data.message || data.error || "未知错误"));
          }
        });
    }
  }
};
